/**
 * @Author       : cxh
 * @Date         : 2021-12-29 13:32:05
 * @LastEditTime : 2021-12-30 10:04:41
 * @LastEditors  : cxh
 * @Description  : 服务端加密
 * @FilePath     : \vue_WorkSpace\egg-wpt-server\app\lib\keyController.js
 */
'use strict';

const NodeRSA = require('node-rsa');
const fs = require('fs');
const path = require('path');

const targetUrl = path.resolve(__dirname, './../config/keys');
class keyController {
  constructor() {
    this.creatKeys = async () => {
      const key = new NodeRSA({
        b: 512,
      });
      const publicKey = key.exportKey('public');
      const privateKey = key.exportKey('private');
      await fs.promises.writeFile(targetUrl + '/publicKey.key', publicKey, {
        encoding: 'utf-8',
      });
      await fs.promises.writeFile(targetUrl + '/privateKey.key', privateKey, {
        encoding: 'utf-8',
      });
      return {
        publicKey,
        privateKey,
      };
    };
    this.getKeys = async () => {
      const dirs = await fs.promises.readdir(targetUrl);
      console.log('dirs', dirs.length);
      if (dirs.length === 0) {
        // 服务端本地没有钥匙文件
        const res = await this.creatKeys();
        return res;
      }
      // 服务端本地有钥匙文件
      const publicKey = await fs.promises.readFile(targetUrl + '/publicKey.key', {
        encoding: 'utf-8',
      });
      return {
        publicKey,
      };
    };
    this.decrypt = async str => {
      // 本地获取私钥
      const res = await fs.promises.readFile(targetUrl + '/privateKey.key', {
        encoding: 'utf-8',
      });
      return new NodeRSA(res).decrypt(str, 'utf-8');
    };
  }
}
module.exports = new keyController();
